package cn.iocoder.an.module.mold.service.linestopcategory;

import cn.hutool.core.collection.CollUtil;
import org.springframework.stereotype.Service;
import jakarta.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import cn.iocoder.an.module.mold.controller.admin.linestopcategory.vo.*;
import cn.iocoder.an.module.mold.dal.dataobject.linestopcategory.LinestopCategoryDO;
import cn.iocoder.an.framework.common.pojo.PageResult;
import cn.iocoder.an.framework.common.pojo.PageParam;
import cn.iocoder.an.framework.common.util.object.BeanUtils;

import cn.iocoder.an.module.mold.dal.mysql.linestopcategory.LinestopCategoryMapper;

import static cn.iocoder.an.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.an.framework.common.util.collection.CollectionUtils.convertList;
import static cn.iocoder.an.framework.common.util.collection.CollectionUtils.diffList;
import static cn.iocoder.an.module.mold.enums.ErrorCodeConstants.*;

/**
 * 停线类型 Service 实现类
 *
 * @author 芋道源码
 */
@Service
@Validated
public class LinestopCategoryServiceImpl implements LinestopCategoryService {

    @Resource
    private LinestopCategoryMapper linestopCategoryMapper;

    @Override
    public Long createLinestopCategory(LinestopCategorySaveReqVO createReqVO) {
        // 校验父id的有效性
        validateParentLinestopCategory(null, createReqVO.getParentId());
        // 校验类型名称的唯一性
        validateLinestopCategoryNameUnique(null, createReqVO.getParentId(), createReqVO.getName());

        // 插入
        LinestopCategoryDO linestopCategory = BeanUtils.toBean(createReqVO, LinestopCategoryDO.class);
        linestopCategoryMapper.insert(linestopCategory);

        // 返回
        return linestopCategory.getId();
    }

    @Override
    public void updateLinestopCategory(LinestopCategorySaveReqVO updateReqVO) {
        // 校验存在
        validateLinestopCategoryExists(updateReqVO.getId());
        // 校验父id的有效性
        validateParentLinestopCategory(updateReqVO.getId(), updateReqVO.getParentId());
        // 校验类型名称的唯一性
        validateLinestopCategoryNameUnique(updateReqVO.getId(), updateReqVO.getParentId(), updateReqVO.getName());

        // 更新
        LinestopCategoryDO updateObj = BeanUtils.toBean(updateReqVO, LinestopCategoryDO.class);
        linestopCategoryMapper.updateById(updateObj);
    }

    @Override
    public void deleteLinestopCategory(Long id) {
        // 校验存在
        validateLinestopCategoryExists(id);
        // 校验是否有子停线类型
        if (linestopCategoryMapper.selectCountByParentId(id) > 0) {
            throw exception(LINESTOP_CATEGORY_EXITS_CHILDREN);
        }
        // 删除
        linestopCategoryMapper.deleteById(id);
    }


    private void validateLinestopCategoryExists(Long id) {
        if (linestopCategoryMapper.selectById(id) == null) {
            throw exception(LINESTOP_CATEGORY_NOT_EXISTS);
        }
    }

    private void validateParentLinestopCategory(Long id, Long parentId) {
        if (parentId == null || LinestopCategoryDO.PARENT_ID_ROOT.equals(parentId)) {
            return;
        }
        // 1. 不能设置自己为父停线类型
        if (Objects.equals(id, parentId)) {
            throw exception(LINESTOP_CATEGORY_PARENT_ERROR);
        }
        // 2. 父停线类型不存在
        LinestopCategoryDO parentLinestopCategory = linestopCategoryMapper.selectById(parentId);
        if (parentLinestopCategory == null) {
            throw exception(LINESTOP_CATEGORY_PARENT_NOT_EXITS);
        }
        // 3. 递归校验父停线类型，如果父停线类型是自己的子停线类型，则报错，避免形成环路
        if (id == null) { // id 为空，说明新增，不需要考虑环路
            return;
        }
        for (int i = 0; i < Short.MAX_VALUE; i++) {
            // 3.1 校验环路
            parentId = parentLinestopCategory.getParentId();
            if (Objects.equals(id, parentId)) {
                throw exception(LINESTOP_CATEGORY_PARENT_IS_CHILD);
            }
            // 3.2 继续递归下一级父停线类型
            if (parentId == null || LinestopCategoryDO.PARENT_ID_ROOT.equals(parentId)) {
                break;
            }
            parentLinestopCategory = linestopCategoryMapper.selectById(parentId);
            if (parentLinestopCategory == null) {
                break;
            }
        }
    }

    private void validateLinestopCategoryNameUnique(Long id, Long parentId, String name) {
        LinestopCategoryDO linestopCategory = linestopCategoryMapper.selectByParentIdAndName(parentId, name);
        if (linestopCategory == null) {
            return;
        }
        // 如果 id 为空，说明不用比较是否为相同 id 的停线类型
        if (id == null) {
            throw exception(LINESTOP_CATEGORY_NAME_DUPLICATE);
        }
        if (!Objects.equals(linestopCategory.getId(), id)) {
            throw exception(LINESTOP_CATEGORY_NAME_DUPLICATE);
        }
    }

    @Override
    public LinestopCategoryDO getLinestopCategory(Long id) {
        return linestopCategoryMapper.selectById(id);
    }

    @Override
    public List<LinestopCategoryDO> getLinestopCategoryList(LinestopCategoryListReqVO listReqVO) {
        return linestopCategoryMapper.selectList(listReqVO);
    }


    @Override
    public List<LinestopCategoryDO> getLineStopCategoryList() {
        return linestopCategoryMapper.selectList();
    }

}